package com.example.sendmail;

import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.Properties;

/**
 * @ClassName TestMail
 * @Description TODO
 * @Author zhangxidong
 * @Date 2020/11/25
 * @Version 1.0
 */
public class TestMail {
	public static void main(String[] args) throws Exception{
		// 1. 创建一封邮件
		Properties props = new Properties();
		Session session = Session.getInstance(props);
		MimeMessage message = new MimeMessage(session);

//		// 也可以根据已有的eml邮件文件创建 MimeMessage 对象
//		MimeMessage message = new MimeMessage(session, new FileInputStream("myEmail.eml"));

		// 2. From: 发件人
		//    其中 InternetAddress 的三个参数分别为: 邮箱, 显示的昵称(只用于显示, 没有特别的要求), 昵称的字符集编码
		//    真正要发送时, 邮箱必须是真实有效的邮箱。
		message.setFrom(new InternetAddress("2436764965@qq.com", "张曦东", "UTF-8"));

		message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress("zhangxidong@outlook.com", "张曦东", "UTF-8"));
		//抄送
//		message.setRecipient(MimeMessage.RecipientType.CC, new InternetAddress("zhangxidong@outlook.com", "张曦东", "UTF-8"));
		//密送
//		message.setRecipient(MimeMessage.RecipientType.BCC, new InternetAddress("zhangxidong@outlook.com", "张曦东", "UTF-8"));

		message.setSubject("this is a test mail", "UTF-8");
		message.setContent("hello world", "text/html;charset=UTF-8");
		message.setSentDate(new Date());
		message.saveChanges();

		OutputStream out = new FileOutputStream("myEmail.eml");
		message.writeTo(out);
		out.flush();
		out.close();
	}
}
